package com.first.core.velocity;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.VelocityStrutsUtil;
import org.apache.struts2.views.util.ContextUtil;
import org.apache.struts2.views.velocity.StrutsVelocityContext;
import org.apache.struts2.views.velocity.VelocityManager;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.context.ChainedContext;

import com.opensymphony.xwork2.util.ValueStack;

public class PlatformVelocityManager extends VelocityManager {

	private static final Logger LOG = Logger
			.getLogger(PlatformVelocityManager.class);

	public Context createContext(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {
		VelocityContext[] chainedContexts = prepareChainedContexts(req, res,
				stack.getContext());
		StrutsVelocityContext context = new StrutsVelocityContext(
				chainedContexts, stack);
		Map standardMap = ContextUtil.getStandardContext(stack, req, res);
		for (Iterator iterator = standardMap.entrySet().iterator(); iterator
				.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			context.put((String) entry.getKey(), entry.getValue());
		}
		context.put(STRUTS, new VelocityStrutsUtil(getVelocityEngine(),
				context, stack, req, res));

		ServletContext ctx = null;
		try {
			ctx = ServletActionContext.getServletContext();
		} catch (NullPointerException npe) {
			// in case this was used outside the lifecycle of struts servlet
			LOG.debug("internal toolbox context ignored");
		}

		if (toolboxManager != null && ctx != null) {

			// here is the new constructor :
			ChainedContext chained = new ChainedContext(context,
					getVelocityEngine(), req, res, ctx);

			chained.setToolbox(toolboxManager.getToolbox(chained));
			return chained;
		} else {
			return context;
		}

	}
}
